package com.hupu.jrs.ui.setting

import android.content.Context
import android.os.Bundle
import android.preference.ListPreference
import android.preference.Preference
import android.preference.PreferenceFragment
import android.preference.PreferenceManager
import android.text.TextUtils
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.hupu.jrs.R
import com.hupu.jrs.injector.HasComponent
import com.hupu.jrs.ui.BaseActivity
import com.hupu.jrs.util.CacheUtil
import com.hupu.jrs.util.FileUtil
import com.hupu.jrs.util.SettingPrefUtil
import com.hupu.jrs.util.ToastUtil
import com.squareup.otto.Bus
import java.io.File
import javax.inject.Inject

/**
 * Created by sll on 2016/3/11.
 */
class SettingFragment : PreferenceFragment(), Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {

    private var pTextSize: ListPreference? = null// 字体大小
    private var pPicSavePath: Preference? = null// 图片保存路径
    private var pClearCache: Preference? = null
    private var pTheme: Preference? = null
    private var pThreadSort: ListPreference? = null
    private var pSwipeBackEdgeMode: ListPreference? = null// 手势返回方向

    @Inject
    internal var mBus: Bus? = null
    @Inject
    internal var mContext: Context? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SettingComponent::class.java.cast((activity as HasComponent<SettingComponent>).component)
                .inject(this)
        addPreferencesFromResource(R.xml.setting)
        val prefs = PreferenceManager.getDefaultSharedPreferences(activity)

        pTextSize = findPreference("pTextSize") as ListPreference
        pTextSize!!.onPreferenceChangeListener = this
        setListSetting(Integer.parseInt(prefs.getString("pTextSize", "4")), R.array.txtSizeNum,
                pTextSize)

        pPicSavePath = findPreference("pPicSavePath")
        pPicSavePath!!.onPreferenceClickListener = this
        pPicSavePath!!.summary = "/sdcard" + File.separator + SettingPrefUtil.getPicSavePath(this!!.mContext!!) + File.separator

        pClearCache = findPreference("pClearCache")
        pClearCache!!.onPreferenceClickListener = this
        pClearCache!!.setSummary(CacheUtil.getCacheSize(this!!.mContext!!))

        pThreadSort = findPreference("pThreadSort") as ListPreference
        pThreadSort!!.onPreferenceChangeListener = this
        setListSetting(Integer.parseInt(prefs.getString("pThreadSort", "0")), R.array.sortType,
                pThreadSort)

        pSwipeBackEdgeMode = findPreference("pSwipeBackEdgeMode") as ListPreference
        pSwipeBackEdgeMode!!.onPreferenceChangeListener = this
        setListSetting(Integer.parseInt(prefs.getString("pSwipeBackEdgeMode", "0")),
                R.array.swipeBackEdgeMode, pSwipeBackEdgeMode)

        pTheme = findPreference("pTheme")
        pTheme!!.onPreferenceClickListener = this
        pTheme!!.summary = resources.getStringArray(R.array.mdColorNames)[SettingPrefUtil.getThemeIndex(
                this!!.mContext!!)]

        //        pOfflineCount = (ListPreference) findPreference("pOfflineCount");
        //        pOfflineCount.setOnPreferenceChangeListener(this);
        //        setListSetting(Integer.parseInt(prefs.getString("pOfflineCount", "0")), R.array.offlineCount, pOfflineCount);

    }

    override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean {
        if ("pTextSize" == preference.key) {
            setListSetting(Integer.parseInt(newValue.toString()), R.array.txtSizeNum, pTextSize)
        } else if ("pThreadSort" == preference.key) {
            setListSetting(Integer.parseInt(newValue.toString()), R.array.sortType, pThreadSort)
        } else if ("pSwipeBackEdgeMode" == preference.key) {
            setListSetting(Integer.parseInt(newValue.toString()), R.array.swipeBackEdgeMode,
                    pSwipeBackEdgeMode)
            (activity as BaseActivity).reload()
        } else if ("pOfflineCount" == preference.key) {
            //  setListSetting(Integer.parseInt(newValue.toString()), R.array.offlineCount, pOfflineCount);
        }
        return true
    }

    override fun onPreferenceClick(preference: Preference): Boolean {
        if ("pPicSavePath" == preference.key) {
            modifyImageSavePath()
        } else if ("pClearCache" == preference.key) {
            cleanCache()
        } else if ("pTheme" == preference.key) {
            ColorsDialogFragment.launch(activity)
        }
        return true
    }

    private fun cleanCache() {
        //        new MaterialDialog.Builder(getActivity()).title("提示").content("正在清空缓存...").progress(true,0).show();
        CacheUtil.cleanApplicationCache(this!!.mContext!!)
        Toast.makeText(activity, "缓存清理成功", Toast.LENGTH_SHORT)
        pClearCache!!.setSummary(CacheUtil.getCacheSize(this!!.mContext!!))
    }

    private fun setTextSize(value: Int) {
        val valueTitleArr = resources.getStringArray(R.array.txtSizeNum)
        pTextSize!!.summary = valueTitleArr[value]
    }

    protected fun setListSetting(value: Int, hintId: Int, listPreference: ListPreference?) {
        val valueTitleArr = resources.getStringArray(hintId)
        listPreference!!.summary = valueTitleArr[value]
    }

    private fun modifyImageSavePath() {
        MaterialDialog.Builder(activity).title("修改图片保存路径")
                .input(null, SettingPrefUtil.getPicSavePath(this!!.mContext!!), MaterialDialog.InputCallback { materialDialog, charSequence ->
                    if (TextUtils.isEmpty(charSequence)) {
                        ToastUtil.showToast("路径不能为空")
                        return@InputCallback
                    }
                    val path = FileUtil.sdcardPath + File.separator + charSequence + File.separator
                    val file = File(path)
                    if (file.exists() || file.mkdirs()) {
                        SettingPrefUtil.setPicSavePath(this!!.mContext!!, charSequence.toString())
                        pPicSavePath!!.summary = "/sdcard" + File.separator + charSequence + File.separator
                        ToastUtil.showToast("更新成功")
                    } else {
                        ToastUtil.showToast("更新失败")
                    }
                })
                .negativeText("取消")
                .show()
    }
}
